package com.love.netty.util;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @ClassName: ChannelSuperviseUtils
 * @Description: 消息推送类
 * @Author: wuj
 * @Date: 2021-07-05 10:07
 **/
public class ChannelSuperviseUtils {

    private static ChannelGroup GlobalGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static ConcurrentMap<String, ChannelId> UserChannelMap = new ConcurrentHashMap();

    private static ConcurrentMap<String, String> ChannelUserMap = new ConcurrentHashMap();


    /**
     * 将用户信息保存到channel
     *
     * @param userId
     * @param channel
     */
    public static void addChannel(String userId, Channel channel) {
        GlobalGroup.add(channel);
        //保存当前key :发送人的userId  value:发送人channel
        UserChannelMap.put(userId, channel.id());
        ChannelUserMap.put(channel.id().asLongText(), userId);
    }

    public static void sendToUser(String userId, String msg) {
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(msg);
        Channel channel = GlobalGroup.find(UserChannelMap.get(userId));
        channel.writeAndFlush(textWebSocketFrame);
    }

    public static void removeChannel(Channel channel) {
        GlobalGroup.remove(channel);
        String userId = ChannelUserMap.get(channel.id().asLongText());
        if (userId != null) {
            UserChannelMap.remove(userId);
            ChannelUserMap.remove(channel.id().asLongText());
        }
    }


    /**
     * 根据用户id  查询到对应的通道
     *
     * @param userId
     * @return
     */
    public static Channel getChannelByUserId(String userId) {
        ChannelId channelId = UserChannelMap.get(userId);
        if(channelId != null){
            return GlobalGroup.find(channelId);
        }else{
            return  null;
        }

    }


    public static String getFromUserIdByChannelId(String longTextId) {
        return ChannelUserMap.get(longTextId);
    }


    public static void sendToAll(String msg) {
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(msg);
        GlobalGroup.writeAndFlush(textWebSocketFrame);
    }
}
